package com.android.studyspot;

import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.app.SherlockFragmentActivity;

import android.app.Dialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.microsoft.windowsazure.mobileservices.MobileServiceClient;
import com.microsoft.windowsazure.mobileservices.MobileServiceTable;
import com.microsoft.windowsazure.mobileservices.ServiceFilterResponse;
import com.microsoft.windowsazure.mobileservices.TableQueryCallback;

public class StudySpotsActivity extends SherlockFragmentActivity {

	protected ArrayList<StudySpot> m_arrStudySpotList;
	
	protected StudySpotListAdapter m_ssAdapter;
	
	protected ListView m_ssLayout;
	
	private MobileServiceTable<vw_users_uc_courses> mUsersCoursesVw;
	
	private MobileServiceTable<vw_studyspot_courses_users> m_coursesUsersTable;
	
	private ArrayList<String> courseList = new ArrayList<String>();
	
	private Bundle hashmap;
	
	private Typeface typeFace;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		typeFace = Typeface.createFromAsset(getAssets(),"fonts/futuraCondensed.ttf");
		
		System.gc();
				
		this.m_arrStudySpotList = new ArrayList<StudySpot>();
		m_ssAdapter = new StudySpotListAdapter(this, m_arrStudySpotList, typeFace);
		hashmap = this.getIntent().getExtras();
		
		initLayout();
				
		getAllStudySpots();
	}

	@Override
    public boolean onKeyDown(int keyCode, KeyEvent event) 
    {
        if(keyCode == KeyEvent.KEYCODE_BACK)
        {
            Intent intent = new Intent(this, UserProfileActivity.class);
            intent.putExtra("userId", hashmap.getInt("userId"));
            startActivity(intent);
            return true;
            
        }
        return false;
    }
	
	private void getAllStudySpots() {
		
		try {
			MobileServiceClient mClient = new MobileServiceClient(
				      "https://studyspot.azure-mobile.net/",
				      "UeeXTmfsscRIhhVuCyRqDRwfThBDPa90",
				      this
			);

			this.mUsersCoursesVw = mClient.getTable(vw_users_uc_courses.class);
			
			this.m_coursesUsersTable = mClient.getTable(vw_studyspot_courses_users.class);
						
			this.m_coursesUsersTable.execute(new TableQueryCallback<vw_studyspot_courses_users>() {

						@Override
						public void onCompleted(List<vw_studyspot_courses_users> result, int count,
								Exception exception, ServiceFilterResponse response) {
							if (exception == null) {
								for (vw_studyspot_courses_users item : result) {
									StudySpot ss = new StudySpot();
									
									ss.setCourse(item.course);
									ss.setStartEndTime(item.starttime + "-" + item.endtime);
									ss.setDate(item.startdate);
									ss.setId(item.ss_id);
									ss.setLocation(item.location);
									ss.setCreator(item.firstname + " " + item.lastname);
									ss.setCreatorEmail(item.email);
									
									addStudySpot(ss);
								}
							}
							else {
								Log.e("StudySpotFoo", exception.getMessage());
							}
							
						}
						
					});			
		}
		catch (MalformedURLException e) {
			Log.d("Azure", e.getMessage());
			e.printStackTrace();
		}
		
	}
	
	private void filterStudySpots() {
		
		try {			
			MobileServiceClient mClient = new MobileServiceClient(
				      "https://studyspot.azure-mobile.net/",
				      "UeeXTmfsscRIhhVuCyRqDRwfThBDPa90",
				      this
			);
			
			mUsersCoursesVw.where().field("usr_id").eq(hashmap.getInt("userId"))
			.execute(new TableQueryCallback<vw_users_uc_courses>() {

				@Override
				public void onCompleted(List<vw_users_uc_courses> result, int count,
						Exception exception, ServiceFilterResponse response) {
					if (exception == null) {
						for (vw_users_uc_courses item : result) {
							courseList.add(item.course);
						}
					}
					else {
						Log.e("StudySpot", exception.getMessage());
					}
					
				}
				
			});
			
			this.m_coursesUsersTable = mClient.getTable(vw_studyspot_courses_users.class);
						
			this.m_coursesUsersTable.execute(new TableQueryCallback<vw_studyspot_courses_users>() {

						@Override
						public void onCompleted(List<vw_studyspot_courses_users> result, int count,
								Exception exception, ServiceFilterResponse response) {
							if (exception == null) {
								for (vw_studyspot_courses_users item : result) {
									
									Log.d("studyspot", item.course);
									Log.d("studyspot", item.crsnum + "_" + item.crsabbrev);
																		
									if(courseList.contains(item.course)){
									
										StudySpot ss = new StudySpot();
										
										ss.setCourse(item.course);
										ss.setStartEndTime(item.starttime + "-" + item.endtime);
										ss.setDate(item.startdate);
										ss.setId(item.ss_id);
										ss.setLocation(item.location);
									
										addStudySpot(ss);
									}
								}
							}
							else {
								Log.e("StudySpotFoo", exception.getMessage());
							}
							
						}
						
					});			
		}
		catch (MalformedURLException e) {
			Log.d("Azure", e.getMessage());
			e.printStackTrace();
		}		
	}

	private void filterStudySpots(final String course) {
		
		try {			
			MobileServiceClient mClient = new MobileServiceClient(
				      "https://studyspot.azure-mobile.net/",
				      "UeeXTmfsscRIhhVuCyRqDRwfThBDPa90",
				      this
			);
			
			mUsersCoursesVw.where().field("usr_id").eq(hashmap.getInt("userId"))
			.execute(new TableQueryCallback<vw_users_uc_courses>() {

				@Override
				public void onCompleted(List<vw_users_uc_courses> result, int count,
						Exception exception, ServiceFilterResponse response) {
					if (exception == null) {
						for (vw_users_uc_courses item : result) {
							courseList.add(item.course);
						}
					}
					else {
						Log.e("StudySpot", exception.getMessage());
					}
					
				}
				
			});
			
			this.m_coursesUsersTable = mClient.getTable(vw_studyspot_courses_users.class);
						
			this.m_coursesUsersTable.execute(new TableQueryCallback<vw_studyspot_courses_users>() {

						@Override
						public void onCompleted(List<vw_studyspot_courses_users> result, int count,
								Exception exception, ServiceFilterResponse response) {
							if (exception == null) {
								for (vw_studyspot_courses_users item : result) {
									
									Log.d("studyspot", item.course);
									Log.d("studyspot", item.crsnum + "_" + item.crsabbrev);
																		
									if(item.course.equals(course)){
									
										StudySpot ss = new StudySpot();
										
										ss.setCourse(item.course);
										ss.setStartEndTime(item.starttime + "-" + item.endtime);
										ss.setDate(item.startdate);
										ss.setId(item.ss_id);
										ss.setLocation(item.location);
									
										addStudySpot(ss);
									}
								}
							}
							else {
								Log.e("StudySpotFoo", exception.getMessage());
							}
							
						}
						
					});			
		}
		catch (MalformedURLException e) {
			Log.d("Azure", e.getMessage());
			e.printStackTrace();
		}		
	}
	
	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getSupportMenuInflater();
        inflater.inflate(R.menu.study_spots_menu, menu);
        
        //add an item for each class
        SharedPreferences pref = getSharedPreferences("userCourses", MODE_PRIVATE);
		HashSet<String> courses;
		
		courses = (HashSet<String>) pref.getStringSet("courses", null);
		
		for(String s: courses){
			menu.add(s);
		}
        
        return true;
    }
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
			case R.id.add_studyspot:
				Intent addStudySpotStart = new Intent(StudySpotsActivity.this, AddStudySpotActivity.class);
				
				addStudySpotStart.putExtra("userId", hashmap.getInt("userId"));
				for (int i=0; i<hashmap.size()-1; i++) {
					addStudySpotStart.putExtra("course-" + i, hashmap.getString("course-" + i));
				}
				startActivity(addStudySpotStart);
				return true;
//			case R.id.refresh_studyspots:
//				this.m_arrStudySpotList.clear();
//				getAllStudySpots();
//				return true;
			case R.id.user_profile:
				Intent userProfileStart = new Intent(StudySpotsActivity.this, UserProfileActivity.class);
				userProfileStart.putExtra("userId", hashmap.getInt("userId"));
				startActivity(userProfileStart);
				return true;
				
			case R.id.filter_studyspots:
				this.m_arrStudySpotList.clear();
				this.m_ssAdapter.notifyDataSetChanged();
				filterStudySpots();
				this.m_ssAdapter.notifyDataSetChanged();
				return true;
			case R.id.show_all_studyspots:
				this.m_arrStudySpotList.clear();
				this.m_ssAdapter.notifyDataSetChanged();
				getAllStudySpots();
				this.m_ssAdapter.notifyDataSetChanged();
				return true;
			default:
				//user selected a class
				Toast.makeText(this, item.getTitle(), Toast.LENGTH_SHORT).show();				
				this.m_arrStudySpotList.clear();
				this.m_ssAdapter.notifyDataSetChanged();
				filterStudySpots((String) item.getTitle());
				this.m_ssAdapter.notifyDataSetChanged();
				return true;
		}
	}

	

	/**
	 * Method is used to encapsulate the code that initializes and sets the
	 * Layout for this Activity.
	 */
	protected void initLayout() {
		setContentView(R.layout.layout_study_spots);
		
		m_ssLayout = (ListView) findViewById(R.id.ss_list_view_group);
		
		m_ssLayout.setAdapter(m_ssAdapter);
		
		m_ssLayout.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				//Toast.makeText(StudySpotsActivity.this, "hello, pos = " + position + ", id = " + m_arrStudySpotList.get(position).getId(), Toast.LENGTH_SHORT).show();
				//Toast.makeText(StudySpotsActivity.this, "course = " + m_arrStudySpotList.get(position).getCourse(), Toast.LENGTH_SHORT).show();
				System.gc();

				StudySpot temp = ((StudySpotView) view).getStudySpot();
				
				StudySpotInfoDialogFragment frag = new StudySpotInfoDialogFragment(temp);

				frag.show(getSupportFragmentManager(), "NoticeDialogFragment");
			}
			
		});
	}

	
	protected void addStudySpot(StudySpot ss){		
		this.m_arrStudySpotList.add(ss);
		this.m_ssAdapter.notifyDataSetChanged();
	}

}
